package com.example.demo1.controller;

import com.example.demo1.mapper.UserMapper;
import com.example.demo1.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author Linyh
 * @Description
 * @Date 2022/5/14 15:45
 **/
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/userList")
    public String allUser(ModelMap modelMap) {
        List<User> users = userMapper.allUser();
        modelMap.put("users", users);
        return "index";
    }

    @GetMapping("/add")
    public String toAddUser() {
        return "user-add";
    }

    @PostMapping("/add")
    public String addUser(User user) {
        userMapper.addUser(user);
        return "redirect:/user/userList";
    }

    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable("id") int id) {
        userMapper.deleteUser(id);
        return "redirect:/user/userList";
    }

    @GetMapping("/updata/{id}")
    public String toUpdataUser(@PathVariable("id") int id, Model model) {
        User user = userMapper.idUser(id);
        model.addAttribute("updata", user);
        return "user-updata";
    }

    @PostMapping("/updata")
    public String updataUser(User user) {
        userMapper.updateUser(user);
        return "redirect:/user/userList";
    }

    @PostMapping("/search")
    public String searchName(User user,ModelMap modelMap) {
        List<User> users = userMapper.searchName(user);
        modelMap.put("users", users);
        return "index";
    }

    @PostMapping("/deleteList")
    public  String deleteUserList(String checkList){
        String[] strs = checkList.split(",");
        List<Integer> id = new ArrayList<>();
        for (String str:strs){
            id.add(Integer.parseInt(str));
        }
        userMapper.deleteList(id);
        return "redirect:/user/userList";
    }


}